package mk.jug.academy.controller;

import mk.jug.academy.model.Content;
import mk.jug.academy.model.Page;
import mk.jug.academy.service.ContentService;
import mk.jug.academy.util.Utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * View layer coordinator for the Blog functionality in the frontend.
 *
 * @author Ice.Penov
 */
@Controller
public class BlogController extends BaseController {
	
	private static final int ITEMS_PER_PAGE = 2;
	
	private static final String LIST_BLOGS = "public.blogs.list";
	private static final String VIEW_BLOG = "public.blogs.view";
	
	@Autowired private ContentService contentService;
	
	@RequestMapping("/blogs.do")
	public String blogs(final ModelMap map, final @RequestParam(value = "page", required = false) Integer p) {
		return new ControllerContext(map) {
			public String execute() {
				Integer page = p;
				if (page == null) {
					page = 1;
				}
				Page<Content> pagedBlogs = contentService.listPublished(page, ITEMS_PER_PAGE);
				map.addAttribute("blogs", pagedBlogs.getItems());
				map.addAttribute("pages", Utils.getPageNumber(ITEMS_PER_PAGE, pagedBlogs.getTotalCount()));
				map.addAttribute("page", page);
				return LIST_BLOGS;
			}
		}.result();
	}
	
	@RequestMapping("/blog.do")
	public String viewBlog(final ModelMap map, final @RequestParam("id") Long id) {
		return new ControllerContext(map) {			
			@Override
			public String execute() {
				Content blog = contentService.load(id);
				map.addAttribute("blog", blog);
				return VIEW_BLOG;
			}
		}.result();
	}

}